﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraTreeList;
using Model;
using Common;
using DevExpress.XtraTreeList.Nodes;
using Controller;
using DevExpress.XtraEditors;
using System.Reflection;
using System.Collections;
using DevExpress.XtraEditors.Controls;

namespace CodeFactory
{
    public partial class CustomPropertyGrid : UserControl
    {

        #region 私有字段

       private Dictionary<string,exFullInfoForBuildChild> _buildDic;
       
       private PropertyGridBO _pgBO;
       
        /// <summary>
       /// 指示当前控件是不是基底
       /// </summary>
       private bool IsBase;

       /// <summary>
       /// 当前控件的信息
       /// </summary>
       private exFullInfoForBuildChild _exFullInfo;

       /// <summary>
       /// 当前基底的信息
       /// </summary>
       private exFullInfoForBuildChild _exFullInfoBase;

       /// <summary>
       /// 当前控件的KEY
       /// </summary>
       private string buildKey;

       /// <summary>
       /// 基底的KEY（唯一，固定）
       /// </summary>
       private static string documentKey = "Document";
        #endregion
        

        #region 属性

       /// <summary>
       ///用于储存从设计器传过来的控件的信息
       /// </summary>
       public exFullInfoForBuildChild exFullInfo 
       { 
           get
           {
               if (_exFullInfo == null)
               {
                   _exFullInfo = new exFullInfoForBuildChild();
               }
               return _exFullInfo;
           }
       }
        

       public PropertyGridBO pgBO
       {
           get
           {
               if (_pgBO == null)
                   _pgBO = FactoryControllerBO.CurrentFA.CreateProperGridBOInstance();
               return _pgBO;
           }

       }


       /// <summary>
       /// key=BuildName,value=exFullInfoForBuildChild
       /// </summary>
       public Dictionary<string, exFullInfoForBuildChild> buildDic
        {
            get
            {
               if(_buildDic==null)
                   _buildDic = new Dictionary<string, exFullInfoForBuildChild>();
               return _buildDic;
            }
            set
            {
               _buildDic=value;
            }
         }

        //public Dictionary<string, exLayoutInfoForBuild> layoutDic
        //{
        //    get

        //}

       public TreeList PropertyTree
       {
           get
           {
               return treeProperty;
           }
       }
	#endregion


        #region 初始化
             
        public CustomPropertyGrid()
        {
            InitializeComponent();
            _exFullInfo = new exFullInfoForBuildChild();
            buildKey = "";
            IsBase = true;
        }
 
       #endregion

       
        #region 私有方法
        

        /// <summary>
        /// 设置按键的选中状态，保证同时只有一个选中
        /// </summary>
        /// <param name="btnClick"></param>
        private void SetPropertyButtonState(enumPropertyBtnClick btnClick)
        {
            switch (btnClick)
            {
                case enumPropertyBtnClick.Property:
                    tsBtnProperty.Checked = true;
                    tsBtnProperty.CheckState = CheckState.Checked;
                    tsBtnEvent.Checked = false;
                    tsBtnEvent.CheckState = CheckState.Unchecked;
                    tsBtnDocument.Checked = false;
                    tsBtnDocument.CheckState = CheckState.Unchecked;
                    tsBtnLayout.Checked = false;
                    tsBtnLayout.CheckState = CheckState.Unchecked;

                    treeColumnMethodType.Visible = false;
                    break;
                case enumPropertyBtnClick.Event:
                    tsBtnProperty.Checked = false;
                    tsBtnProperty.CheckState = CheckState.Unchecked;
                    tsBtnEvent.Checked = true;
                    tsBtnEvent.CheckState = CheckState.Checked;
                    tsBtnDocument.Checked = false;
                    tsBtnDocument.CheckState = CheckState.Unchecked;
                    tsBtnLayout.Checked = false;
                    tsBtnLayout.CheckState = CheckState.Unchecked;

                    treeColumnMethodType.Visible = false;
                    break;
                case enumPropertyBtnClick.Document:
                    tsBtnProperty.Checked = false;
                    tsBtnProperty.CheckState = CheckState.Unchecked;
                    tsBtnEvent.Checked = false;
                    tsBtnEvent.CheckState = CheckState.Unchecked;
                    tsBtnDocument.Checked = true;
                    tsBtnDocument.CheckState = CheckState.Checked;
                    tsBtnLayout.Checked = false;
                    tsBtnLayout.CheckState = CheckState.Unchecked;

                    treeColumnMethodType.Visible = true;
                    break;
                case enumPropertyBtnClick.Layout:
                    tsBtnProperty.Checked = false;
                    tsBtnProperty.CheckState = CheckState.Unchecked;
                    tsBtnEvent.Checked = false;
                    tsBtnEvent.CheckState = CheckState.Unchecked;
                    tsBtnDocument.Checked = false;
                    tsBtnDocument.CheckState = CheckState.Unchecked;
                    tsBtnLayout.Checked = true;
                    tsBtnLayout.CheckState = CheckState.Checked;

                    treeColumnMethodType.Visible = false;
                    break;
                case enumPropertyBtnClick.AZ:
                    tsBtnAZ.Checked = true;
                    tsBtnAZ.CheckState = CheckState.Checked;
                    tsBtnZA.Checked = false;
                    tsBtnZA.CheckState = CheckState.Unchecked;
                    break;
                case enumPropertyBtnClick.ZA:
                    tsBtnAZ.Checked = false;
                    tsBtnAZ.CheckState = CheckState.Unchecked;
                    tsBtnZA.Checked = true;
                    tsBtnZA.CheckState = CheckState.Checked;
                    break;
            }
        }

        /*------------------------------------------------------------------------------------*/


        /// <summary>
        /// 从当前属性表获取属性列表
        /// </summary>
        /// <param name="_enumPBC"></param>
        /// <returns></returns>
        private List<eProperty> GetPropertyFromNowGrid()
        {
            if (tsBtnDocument.CheckState == CheckState.Checked)
            {
                List<eProperty> list = new List<eProperty>();
                eProperty ep = null;
                foreach (TreeListNode tln in treeProperty.Nodes)
                {
                    ep = new eProperty();

                    List<eMethodParam> listParam = null;
                    if (tln.HasChildren && tln.GetValue(4).ToString().Trim()=="Method")
                    {
                        listParam = new List<eMethodParam>();
                        foreach (TreeListNode tlnChild in tln.Nodes)
                        {
                            eMethodParam emp = new eMethodParam();
                            emp.ParamName = tlnChild.GetValue(0).ToString();
                            emp.DataType = tlnChild.GetValue(1)==null?"":tlnChild.GetValue(1).ToString().Split('-')[0];
                            emp.OutputType = tlnChild.GetValue(1) == null?"none":tlnChild.GetValue(1).ToString().Split('-')[1];
                            listParam.Add(emp);
                        }
                    }

                    List<eInherit> listInherit = null;
                    if (tln.HasChildren && tln.GetValue(4).ToString().Trim() == "Inherit")
                    {
                        listInherit = new List<eInherit>();
                        foreach (TreeListNode tlnChild in tln.Nodes)
                        {
                            eInherit ei = new eInherit();
                            ei.Name = tlnChild.GetValue(0).ToString();
                            ei.Type = (enumInheritType)Enum.Parse(typeof(enumInheritType), tlnChild.GetValue(1).ToString(), false);
                            listInherit.Add(ei);
                        }
                    }

                    ep.ParamList = listParam;
                    ep.InheritList = listInherit;
                    ep.Name = tln.GetValue(0).ToString();
                    ep.Value = tln.GetValue(1) == null ? "" : tln.GetValue(1).ToString().Trim();
                    ep.ValueType = tln.GetValue(2) == null ? "String" : tln.GetValue(2).ToString().Trim();//默认为String类型
                    ep.ValueTypeFullName = tln.GetValue(3) == null ? "" : tln.GetValue(3).ToString().Trim();
                    ep.PropertyType = (enumPropertyType)Enum.Parse(typeof(enumPropertyType), tln.GetValue(4).ToString().Trim());
                    ep.Accessibility = tln.GetValue(5) == null ? "" : tln.GetValue(5).ToString().Trim();
                    ep.ReturnType = tln.GetValue(6) == null ? "" : tln.GetValue(6).ToString().Trim();
                    ep.Attribute = tln.GetValue(7) == null ? "" : tln.GetValue(7).ToString().Trim();
                    ep.EventArgs = tln.GetValue(8) == null ? "" : tln.GetValue(8).ToString().Trim();
                    
                    list.Add(ep);
                }    
                return list;
            }
            else
            {
                List<eProperty> list = new List<eProperty>();
                eProperty ep = null;
                foreach (TreeListNode tln in treeProperty.Nodes)
                {
                    ep = new eProperty();

                    ep.Name = tln.GetValue(0).ToString();
                    ep.Value = tln.GetValue(1) == null ? "" : tln.GetValue(1).ToString().Trim();
                    ep.ValueType = tln.GetValue(2) == null ? "String" : tln.GetValue(2).ToString().Trim();//默认为String类型
                    ep.ValueTypeFullName = tln.GetValue(3) == null ? "" : tln.GetValue(3).ToString().Trim();
                    ep.PropertyType = (enumPropertyType)Enum.Parse(typeof(enumPropertyType), tln.GetValue(4).ToString().Trim());
                    ep.Accessibility = tln.GetValue(5) == null ? "" : tln.GetValue(5).ToString().Trim();
                    ep.ReturnType = tln.GetValue(6) == null ? "" : tln.GetValue(6).ToString().Trim();
                    ep.Attribute = tln.GetValue(7) == null ? "" : tln.GetValue(7).ToString().Trim();
                    ep.EventArgs = tln.GetValue(8) == null ? "" : tln.GetValue(8).ToString().Trim();

                    list.Add(ep);
                }
                return list;
            }
        }


        /*------------------------------------------------------------------------------------*/


        /// <summary>
        /// 保存单击鼠标获取的控件信息
        /// 如果内存中不存在KEY，则从模板读取并添加
        /// 如果有KEY值，则更新
        /// 更新Key为控件的BuildName
        /// </summary>
        /// <param name="exInfo">信息</param>
        private void SaveControlInfo(exFullInfoForBuildChild exInfo,bool IsLayout)
        {
            _exFullInfo = exInfo.DeepCopy(); 
            buildKey = _exFullInfo.BuildName;

            if (!buildDic.ContainsKey(buildKey))
            {
                //内存中没有空间模板，则先从模板文件加载
                List<eProperty> listAll;
                if (IsLayout)
                {
                    listAll = pgBO.GetLayoutInfoFromTemplate(exInfo.LayoutType).PropertyList;
                }
                else
                {
                    listAll = pgBO.GetControlTemplateInfo(_exFullInfo.ControlName, _exFullInfo.ControlClass);
                    //_exFullInfo.PropertyList = listAll;
                    //buildDic.Add(buildKey, _exFullInfo);
                }
                //更新模板中的一些已经获取到的值
                for (int i=0; i < listAll.Count; i++)
                {
                    switch (listAll[i].Name)
                    {
                        case "Name": listAll[i].Value = _exFullInfo.BuildName;
                            break;
                        case "Text": if (IsLayout) listAll[i].Value = _exFullInfo.LayoutText;
                            break;
                        case "Control": if (IsLayout) listAll[i].Value = _exFullInfo.InControl;
                            break;
                        case "CustomizationFormText": if (IsLayout) listAll[i].Value = _exFullInfo.LayoutText;
                            break;
                    }
                }

                //更新后的值添加进内存
                _exFullInfo.PropertyList = listAll;
                buildDic.Add(buildKey, _exFullInfo);
            }
            else//内存中有则更新
            {   
                if (IsLayout)
                {
                    //更新属性
                    SaveUpdatedPropertyInfo();
                }
                //更行控件
                dicUpdate(buildKey, _exFullInfo);
            }

        }


        /// <summary>
        /// 保存并更新基底控件信息
        /// </summary>
        /// <param name="exInfo"></param>
        private void SaveControlInfoBase(exFullInfoForBuildChild exInfo)
        {
            _exFullInfoBase = exInfo.DeepCopy();

            dicUpdate(documentKey, _exFullInfoBase);
        }



        /*------------------------------------------------------------------------------------*/

        /// <summary>
        /// 储存对属性列表做出的修改
        /// </summary>
        private void SaveUpdatedPropertyInfo()
        {
            if (tsBtnDocument.CheckState == CheckState.Checked)
            {
                dicUpdate(documentKey, GetPropertyFromNowGrid());
            }
            else
            {
                if (IsBase)
                {
                    dicUpdate(documentKey, GetPropertyFromNowGrid());
                }
                else
                { 
                  if (!String.IsNullOrEmpty(buildKey))
                  {
                    dicUpdate(buildKey, GetPropertyFromNowGrid());
                  }
                }
            }
        }
        #endregion


        #region Dictionary方法

        /// <summary>
        /// 如果存在相同的属性名则不添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="_ep"></param>
        public void dicAdd(string key, eProperty _ep)
        {
            exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];
            int num = 0;
            foreach (eProperty ep in exFInfo.PropertyList)
            {
                if (_ep.Name.Equals(ep.Name))
                {
                    num++;
                    break;
                }
            }
            if (num == 0)
            {
                exFInfo.PropertyList.Add(_ep);
            }
            buildDic[key] = exFInfo;
        }

        /// <summary>
        /// 如果存在相同的属性名则不添加
        /// </summary>
        /// <param name="key"></param>
        /// <param name="_ep"></param>
        public void dicAdd(string key, eInherit ei)
        {
            exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];

            for (int i = 0; i < exFInfo.PropertyList.Count; i++)
            {
                if (exFInfo.PropertyList[i].PropertyType == enumPropertyType.Inherit)
                {
                    int num = 0;
                    foreach (eInherit e in exFInfo.PropertyList[i].InheritList)
                    {
                        if (e.Name == ei.Name)
                        {
                            num++;
                            break;
                        }
                    }
                    if (num == 0)
                    {
                        exFInfo.PropertyList[i].InheritList.Add(ei);
                    }
                    break;
                }
            }

            buildDic[key] = exFInfo;
        }

        ///// <summary>
        ///// 如果存在相同的属性名则不添加
        ///// </summary>
        ///// <param name="key"></param>
        ///// <param name="_ep"></param>
        //public void dicAdd(string key, List<string> controlsList)
        //{
        //    exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];

        //    for (int i = 0; i < exFInfo.PropertyList.Count; i++)
        //    {
        //        if (exFInfo.PropertyList[i].PropertyType == enumPropertyType.Inherit)
        //        {
        //            int num = 0;
        //            foreach (eInherit e in exFInfo.PropertyList[i].InheritList)
        //            {
        //                if (e.Name == ei.Name)
        //                {
        //                    num++;
        //                    break;
        //                }
        //            }
        //            if (num == 0)
        //            {
        //                exFInfo.PropertyList[i].InheritList.Add(ei);
        //            }
        //            break;
        //        }
        //    }

        //    buildDic[key] = exFInfo;
        //}

        /// <summary>
        /// 如果存在相同的属性名则排除
        /// </summary>
        /// <param name="key"></param>
        /// <param name="_list">属性列表</param>
        public void dicAdd(string key, List<eProperty> _list)
        {
            try
            {
                exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];
                _list.ForEach(_ep =>
                {
                    int num = 0;
                    foreach (eProperty ep in exFInfo.PropertyList)
                    {
                        if (_ep.Name.Equals(ep.Name))
                        {
                            num++;
                            break;
                        }
                    }
                    if (num == 0)
                    {
                        exFInfo.PropertyList.Add(_ep);
                    }
                });
                buildDic[key] = exFInfo;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 添加一个KEY,VALUE组合
        /// </summary>
        /// <param name="key"></param>
        /// <param name="ex"></param>
        public void dicAdd(string key, exFullInfoForBuildChild ex)
        {
            buildDic.Add(key, ex);
        }

        /// <summary>
        /// 移除一个指定的属性
        /// </summary>
        /// <param name="ep"></param>
        /// <param name="key"></param>
        public void dicRemove(string key, eProperty ep)
        {
            exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];
            exFInfo.PropertyList.Remove(ep);
            buildDic[key] = exFInfo;
        }

        /// <summary>
        /// 移除一个指定属性名的属性项
        /// </summary>
        /// <param name="key"></param>
        /// <param name="_propertyName"></param>
        /// <param name="Type">param,inherit或者空""</param>
        public void dicRemove(string key, string _propertyName)
        {
            exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];
            exFInfo.PropertyList.Remove(exFInfo.PropertyList.Find(p => String.Compare(p.Name, _propertyName, false) == 0));
            buildDic[key] = exFInfo;
        }


        /// <summary>
        /// 移除一个参数或者继承项
        /// </summary>
        /// <param name="key"></param>
        /// <param name="tln"></param>
        /// <param name="sType">Parameter,Inherit</param>
        public void dicRemove(string key, TreeListNode tln, string sType)
        {
            exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];
            switch (sType)
            {
                case "Parameter": exFInfo.PropertyList.Find(p => String.Compare(p.Name, tln.ParentNode.GetValue(0).ToString(), false) == 0).ParamList.Remove(exFInfo.PropertyList.Find(p => String.Compare(p.Name, tln.ParentNode.GetValue(0).ToString(), false) == 0).ParamList.Find(p => String.Compare(p.ParamName, tln.GetValue(0).ToString(), false) == 0));
                    break;
                case "Inherit": exFInfo.PropertyList.Find(p => String.Compare(p.Name, tln.ParentNode.GetValue(0).ToString(), false) == 0).InheritList.Remove(exFInfo.PropertyList.Find(p => String.Compare(p.Name, tln.ParentNode.GetValue(0).ToString(), false) == 0).InheritList.Find(p => String.Compare(p.Name, tln.GetValue(0).ToString(), false) == 0));
                    break;
            }

            buildDic[key] = exFInfo;
        }

        /// <summary>
        /// 移除一个key值
        /// </summary>
        /// <param name="key"></param>
        public void dicRemove(string key)
        {
            if (!buildDic.ContainsKey(key))
                return;
            buildDic.Remove(key);
        }

        /// <summary>
        /// 清除所有Dictionary信息
        /// </summary>
        /// <returns></returns>
        public void dicClean()
        {
            buildDic.Clear();
        }

        /// <summary>
        /// 将更新的过的属性列表保存
        /// </summary>
        /// <param name="_list"></param>
        /// <param name="key"></param>
        public void dicUpdate(string key, List<eProperty> _list)
        {
            exFullInfoForBuildChild ex = (exFullInfoForBuildChild)buildDic[key];
            _list.ForEach(_ep =>
            {
                for (int i = 0; i < ex.PropertyList.Count; i++)
                {
                    if (_ep.Name.Equals(ex.PropertyList[i].Name))
                    {
                        ex.PropertyList[i].Accessibility = _ep.Accessibility;
                        ex.PropertyList[i].Attribute = _ep.Attribute;
                        ex.PropertyList[i].EventArgs = _ep.EventArgs;
                        ex.PropertyList[i].ParamList = _ep.ParamList;
                        ex.PropertyList[i].PropertyType = _ep.PropertyType;
                        ex.PropertyList[i].ReturnType = _ep.ReturnType;
                        ex.PropertyList[i].Value = _ep.Value;
                        ex.PropertyList[i].ValueType = _ep.ValueType;
                        ex.PropertyList[i].ValueTypeFullName = _ep.ValueTypeFullName;
                        break;
                    }
                }
            });
            buildDic[key] = ex;
        }

        /// <summary>
        /// 更新控件信息（不包括属性列表）
        /// </summary>
        /// <param name="_list"></param>
        /// <param name="key"></param>
        public void dicUpdate(string key, exFullInfoForBuildChild _exFInfo)
        {
            exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];
            exFInfo.BuildName = _exFInfo.BuildName;
            exFInfo.ControlClass = _exFInfo.ControlClass;
            exFInfo.ControlFullName = _exFInfo.ControlFullName;
            exFInfo.ControlName = _exFInfo.ControlName;
            exFInfo.InControl = _exFInfo.InControl;
            exFInfo.IsLayout = _exFInfo.IsLayout;
            exFInfo.LayoutText=_exFInfo.LayoutText;
            exFInfo.LayoutType = _exFInfo.LayoutType;
            exFInfo.ParentLayoutName = _exFInfo.ParentLayoutName;
            exFInfo.ControlsList = _exFInfo.ControlsList;
            exFInfo.ChildNodes = _exFInfo.ChildNodes;
            exFInfo.IsBase = _exFInfo.IsBase;
            exFInfo.FieldName = _exFInfo.FieldName;
            exFInfo.FieldType = _exFInfo.FieldType;
            buildDic[key] = exFInfo;
        }

        /// <summary>
        /// 将更新的过的属性保存
        /// </summary>
        /// <param name="ep"></param>
        /// <param name="key"></param>
        public void dicUpdate(string key, eProperty ep)
        {
            exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[key];
            for (int i = 0; i < exFInfo.PropertyList.Count; i++)
            {
                if (ep.Name.Equals(exFInfo.PropertyList[i].Name))
                {
                    exFInfo.PropertyList[i].Accessibility = ep.Accessibility;
                    exFInfo.PropertyList[i].Attribute = ep.Attribute;
                    exFInfo.PropertyList[i].EventArgs = ep.EventArgs;
                    exFInfo.PropertyList[i].ParamList = ep.ParamList;
                    exFInfo.PropertyList[i].PropertyType = ep.PropertyType;
                    exFInfo.PropertyList[i].ReturnType = ep.ReturnType;
                    exFInfo.PropertyList[i].Value = ep.Value;
                    exFInfo.PropertyList[i].ValueType = ep.ValueType;
                    exFInfo.PropertyList[i].ValueTypeFullName = ep.ValueTypeFullName;
                    break;
                }
            }
            buildDic[key] = exFInfo;
        }

        /// <summary>
        /// 修改Key值
        /// </summary>
        /// <param name="newKey">新Key</param>
        /// <param name="oldKey">老Key</param>
        /// <returns>
        /// 0:更新成功
        /// 1:oldKey不存在（异常）
        /// 2:newKey已经存在（异常）
        /// </returns>
        public int dicUpdateKey(string oldKey, string newKey)
        {
            if (!buildDic.ContainsKey(oldKey))
            {
                return 1;
            }
            if (buildDic.ContainsKey(newKey))
            {
                return 2;
            }
            exFullInfoForBuildChild exFInfo = (exFullInfoForBuildChild)buildDic[oldKey];
            buildDic.Remove(oldKey);
            buildDic.Add(newKey, exFInfo);
            return 0;
        }

        /// <summary>
        /// 从内存Hashtable中获得指定种类的属性列表
        /// </summary>
        /// <param name="key">空间的生成名（key）</param>
        /// <param name="_enumPBC">属性种类</param>
        /// <returns></returns>
        public List<eProperty> dicGet(string key, enumPropertyType _enumPBC)
        {
            List<eProperty> list = new List<eProperty>();
            foreach (eProperty ep in ((exFullInfoForBuildChild)buildDic[key]).PropertyList)
            {
                if (ep.PropertyType == _enumPBC)
                {
                    list.Add(ep);
                }
            }
            return list;
        }

        /// <summary>
        /// 排除某些属性，然后输出
        /// (比如不显示Event和Method,则将Event和Method名添加进List《string》中)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="listS">需要排除取出的属性名称列表</param>
        /// <returns></returns>
        public List<eProperty> dicGet(string key, List<string> listS)
        {
            List<eProperty> listAll = ((exFullInfoForBuildChild)buildDic[key]).PropertyList;
            List<eProperty> list = new List<eProperty>();
            foreach (eProperty ep in listAll)
            {
                if (!listS.Contains(ep.PropertyType.ToString()))
                {
                    list.Add(ep);
                }
            }

            return list;
        }



        #endregion



        #region 可供外部调用的公共方法
    

        /*外部调用添加控件------------------------------------------------------------------------------------*/


        /// <summary>
        /// 添加属性项到树
        /// </summary>
        /// <param name="ht"></param>
        public void AddPropertysToTree(List<eProperty> _list,enumPropertyType _enumPT)
        {
            try
            {
                switch(_enumPT)
                {
                    case enumPropertyType.Property:
                        SetPropertyButtonState(enumPropertyBtnClick.Property);
                        break;
                    case enumPropertyType.Event:
                        SetPropertyButtonState(enumPropertyBtnClick.Event);
                        break;
                }
                if (IsBase)
                {
                    dicAdd(documentKey, _list);
                    GetPropertyToGridBase(_exFullInfoBase, _enumPT, false);
                }
                else
                {
                    dicAdd(buildKey, _list);
                    GetPropertyToGrid(_exFullInfo, _enumPT, false);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        /// <summary>
        /// 添加方法，字段等到Document树
        /// </summary>
        /// <param name="ep"></param>
        public void AddMethodsToTree(eProperty ep)
        {
          SetPropertyButtonState(enumPropertyBtnClick.Document);

          dicAdd(documentKey, ep);

          GetDocumentToGrid(buildDic[documentKey].BaseType);        
        }

        /// <summary>
        /// 往方法中添加代码
        /// </summary>
        /// <param name="ex"></param>
        public void AddMethodCodeToTree(eProperty ex)
        {
            treeProperty.FocusedNode.SetValue("PropertyValue",ex.Value);

            SaveUpdatedPropertyInfo();
        }


        /// <summary>
        /// 添加继承项目
        /// </summary>
        /// <param name="ei"></param>
        public void AddInheritItemToTree(eInherit ei)
        {
            SetPropertyButtonState(enumPropertyBtnClick.Document);
            
            dicAdd(documentKey, ei);
            
            GetDocumentToGrid(buildDic[documentKey].BaseType);
        }



        /*按钮状态改变------------------------------------------------------------------------------------*/


        /// <summary>
        /// 单击一个左边控件时，如果Document按钮选中则改成Property按钮选中
        /// </summary>
        public void ChangePropertyButtonState(bool IsLayout)
        {
            if (IsLayout)
            {
                SetPropertyButtonState(enumPropertyBtnClick.Layout);
            }
            else
            {
                if (tsBtnDocument.CheckState == CheckState.Checked||tsBtnLayout.CheckState==CheckState.Checked)
                {
                    SetPropertyButtonState(enumPropertyBtnClick.Property);
                }
            }
        }



        /// <summary>
        /// 判断是不是单击的基底
        /// 设置自定义按钮的可用与否（选中基底控件的时候才可用）
        /// </summary>
        /// <param name="IsEnable"></param>
        public void SetButtonStatus(bool IsClickBase,bool IsClickLayout)
        {
            if (IsClickBase)
            {
                //tsBtnCustomProperty.Enabled = true;
                //tsBtnCustomEvent.Enabled = true;
                tsBtnNewCustomEvent.Enabled = true;
                tsBtnNewCustomProperty.Enabled = true;

                tsBtnNewEvent.Enabled = true;
                tsBtnNewProperty.Enabled = true;

                tsBtnNewMethodTemp.Enabled = true;
                tsBtnNewField.Enabled = true;
                tsBtnNewMethod.Enabled = true;
                tsBtnDocument.Enabled = true;

                tsBtnNewInherit.Enabled = true;

                IsBase = true;
            }
            else
            {
                //tsBtnCustomProperty.Enabled = false;
                //tsBtnCustomEvent.Enabled = false;
                tsBtnNewCustomEvent.Enabled = false;
                tsBtnNewCustomProperty.Enabled = false;

                tsBtnNewEvent.Enabled = true;
                tsBtnNewProperty.Enabled = true;

                tsBtnNewField.Enabled = false;
                tsBtnNewMethod.Enabled = false;
                tsBtnDocument.Enabled = false;
                tsBtnNewMethodTemp.Enabled = false;

                tsBtnNewInherit.Enabled = false;

                IsBase = false;
            }

            if (IsClickLayout)
            {
                tsBtnLayout.Enabled = true;
                tsBtnEvent.Enabled = false;
                tsBtnProperty.Enabled = false;
                tsBtnDocument.Enabled = false;
            }
            else
            {
                tsBtnLayout.Enabled = false;
                tsBtnEvent.Enabled = true;
                tsBtnProperty.Enabled = true;
                tsBtnDocument.Enabled = true;
            }
        }


        /*添加控件属性的主要方法------------------------------------------------------------------------------------*/


        /// <summary>
        /// 获取控件的属性信息并加载到属性表
        /// 第一次从模板载入，保存到内存，之后从内存载入
        /// </summary>
        /// <param name="exInfo">需要生成的控件的信息</param>
        /// <param name="propertyType">需要处理的属性类型（属性，方法，事件等）</param>
        /// <param name="IsOutSideCall">是不是从外部调用</param>
        public void GetPropertyToGrid(exFullInfoForBuildChild exInfo, enumPropertyType propertyType, bool IsOutSideCall)
        {
            if (IsOutSideCall)//从外部调用的时候将控件信息保存
            {
                SaveControlInfo(exInfo,false);
            }

            if (String.IsNullOrEmpty(_exFullInfo.BuildName))
            {
                treeProperty.Nodes.Clear();
                return;
            }

            //根据按键状态获取种类
            if (tsBtnProperty.CheckState == CheckState.Checked)
            {
                propertyType = enumPropertyType.Property;
            }
            if (tsBtnEvent.CheckState == CheckState.Checked)
            {
                propertyType = enumPropertyType.Event;
            }

            //从内存中加载
            List<eProperty> list = dicGet(buildKey, propertyType);
            treeColumnMethodType.Visible = false;
            treeProperty.Nodes.Clear();
            foreach (eProperty ep in list)
            {
                TreeListNode tln = treeProperty.AppendNode(null, null);
                tln.SetValue(0, ep.Name);
                if (String.Compare(ep.Name, "Name", false) == 0)
                {
                    tln.SetValue(1, _exFullInfo.BuildName);
                }
                else
                {
                    tln.SetValue(1, ep.Value);
                }
                tln.SetValue(2, ep.ValueType);
                tln.SetValue(3, ep.ValueTypeFullName);
                tln.SetValue(4, ep.PropertyType);
                tln.SetValue(5, ep.Accessibility);
                tln.SetValue(6, ep.ReturnType);
                tln.SetValue(7, ep.Attribute);
                tln.SetValue(8, ep.EventArgs);
            }
        }
        


        /// <summary>
        /// 从内存中（新建工程时已经加载到内存中）获取基底的控件信息，并加载到属性表
        /// </summary>
        /// <param name="exInfo"></param>
        /// <param name="propertyType"></param>
        /// <param name="IsOutSideCall"></param>
        public void GetPropertyToGridBase(exFullInfoForBuildChild exInfo, enumPropertyType propertyType, bool IsOutSideCall)
        {
            if (IsOutSideCall)//从外部调用的时候将基底信息保存
            {
                SaveControlInfoBase(exInfo);
            }

            //根据按键状态获取种类
            if (tsBtnProperty.CheckState == CheckState.Checked)
            {
                propertyType = enumPropertyType.Property;
            }
            if (tsBtnEvent.CheckState == CheckState.Checked)
            {
                propertyType = enumPropertyType.Event;
            }

             
            //从内存中加载(新建工程时，已经加载进内存中)
            List<eProperty> list = dicGet(documentKey, propertyType);
            treeColumnMethodType.Visible = false;
            treeProperty.Nodes.Clear();
            foreach (eProperty ep in list)
            {
                TreeListNode tln = treeProperty.AppendNode(null, null);
                tln.SetValue(0, ep.Name);
                if (ep.Name == "Name")
                {
                    tln.SetValue(1, _exFullInfoBase == null ? "" : _exFullInfoBase.BuildName);
                }
                else
                {
                    tln.SetValue(1, ep.Value);
                }
                tln.SetValue(2, ep.ValueType);
                tln.SetValue(3, ep.ValueTypeFullName);
                tln.SetValue(4, ep.PropertyType);
                tln.SetValue(5, ep.Accessibility);
                tln.SetValue(6, ep.ReturnType);
                tln.SetValue(7, ep.Attribute);
                tln.SetValue(8, ep.EventArgs); ;
            }
        }


        
        /// <summary>
        /// 获取Document的属性信息,并加载到属性表
        /// 第一次从模板载入，保存到内存，之后从内存载入
        /// </summary>
        public void GetDocumentToGrid(enumBaseControlType enumBase)
        {
            try
            {
                //首次通过模板读取控件属性信息，保存进内存，之后从内存中读取
                if (!buildDic.ContainsKey(documentKey))
                {   
                    //内存中没有空间模板，则先从模板文件加载
                 exFullInfoForBuildChild exFInfo = pgBO.GetBaseTypeInfoFromTemplate(enumBase);
                    exFInfo.IsBase = true;
                    exFInfo.BaseType = enumBase;
                    exFInfo.PropertyList = pgBO.GetDocumentTemplateInfo(exFInfo.BaseType);
                    dicAdd(documentKey, exFInfo);
                }

                //从内存中加载
                List<string> listS=new List<string>();
                listS.Add(enumPropertyType.Property.ToString());//不显示属性页
                listS.Add(enumPropertyType.Event.ToString());//不显示事件

                List<eProperty> list = dicGet(documentKey,listS);

                treeColumnMethodType.Visible = true;
                treeProperty.Nodes.Clear();
              
                foreach (eProperty ep in list)
                {
                   TreeListNode tln = treeProperty.AppendNode(null, null);
                   tln.SetValue(0, ep.Name);
                   tln.SetValue(1, ep.Value);
                   tln.SetValue(2, ep.ValueType);
                   tln.SetValue(3, ep.ValueTypeFullName);
                   tln.SetValue(4, ep.PropertyType);
                   tln.SetValue(5, ep.Accessibility);
                   tln.SetValue(6, ep.ReturnType);
                   tln.SetValue(7, ep.Attribute);
                   tln.SetValue(8, ep.EventArgs);
                   if (ep.ParamList != null)
                   {
                      foreach(eMethodParam emp in ep.ParamList)
                      {
                         TreeListNode tlnChild = treeProperty.AppendNode(null, tln.Id);
                         tlnChild.SetValue(0, emp.ParamName);
                         tlnChild.SetValue(1, String.Format("{0}-{1}", emp.OutputType, emp.DataType));
                         tlnChild.SetValue(2, "String");
                         //tlnChild.SetValue(3, "");
                         tlnChild.SetValue(4, "Parameter");
                      }                 
                   }
                   if (ep.InheritList != null)
                   {
                       foreach (eInherit ei in ep.InheritList)
                       {
                           TreeListNode tlnChild = treeProperty.AppendNode(null, tln.Id);
                           tlnChild.SetValue(0, ei.Name);
                           tlnChild.SetValue(1, ei.Type.ToString());
                           tlnChild.SetValue(2, "String");
                           tlnChild.SetValue(4, "Inherit");
                       }
                   }
                } 
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取Layout属性信息，并加载到属性表
        /// 第一次从模板载入，保存早内存，之后从内存载入
        /// </summary>
        /// <param name="exLayout"></param>
        public void GetLayoutToGrid(exFullInfoForBuildChild exLayout)
        {
            try
            {

                SaveControlInfo(exLayout,true);

                //if (exLayout.LayoutType == enumLayoutType.LayoutControl)
                //{
                //    dicAdd(documentKey,)
                //}
                if (String.IsNullOrEmpty(_exFullInfo.BuildName))
                {
                    treeProperty.Nodes.Clear();
                    return;
                }

                //从内存中加载
                List<eProperty> list = dicGet(buildKey, enumPropertyType.Property);
                treeColumnMethodType.Visible = false;
                treeProperty.Nodes.Clear();
                foreach (eProperty ep in list)
                {
                    TreeListNode tln = treeProperty.AppendNode(null, null);
                    tln.SetValue(0, ep.Name);
          
                    switch(ep.Name)
                    {
                       case"Name":                   tln.SetValue(1, _exFullInfo.BuildName);   break;
                       case"Text":                   tln.SetValue(1, _exFullInfo.LayoutText);  break;
                       case"CustomizationFormText":  tln.SetValue(1, _exFullInfo.LayoutText);  break;
                       case"Control":                tln.SetValue(1, _exFullInfo.InControl);   break;
         
                       default:                      tln.SetValue(1, ep.Value);                break;
                    }

                    tln.SetValue(2, ep.ValueType);
                    tln.SetValue(3, ep.ValueTypeFullName);
                    tln.SetValue(4, ep.PropertyType);
                    tln.SetValue(5, ep.Accessibility);
                    tln.SetValue(6, ep.ReturnType);
                    tln.SetValue(7, ep.Attribute);
                    tln.SetValue(8, ep.EventArgs);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        
        #endregion


        #region 树事件

        /// <summary>
        /// 根据Tree的单元格数据种类来绑定不同的控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeProperty_CustomNodeCellEdit(object sender, GetCustomNodeCellEditEventArgs e)
        {
            if (e.Column.Name == "treeColumnPropertyName")      return;
            if (e.Column.Name == "treeColumnPropertyValueType") return;
            if (e.Column.Name == "treeColumnPropertyFullType")  return;
            if (e.Column.Name == "treeColumnMethodType")        return;
            if (e.Column.Name == "treeColumnAccessibility")     return;
            if (e.Column.Name == "treeColumnAttribute")         return;
            if (e.Column.Name == "treeColumnReturnType")        return;
            if (e.Column.Name == "treeColumnEventArgs")         return;

            object obj = e.Node.GetValue("PropertyValueType");//取得数据类型这一栏
            if (obj == null) return;
            
            switch(obj.ToString())
             {
               case "Boolean":        e.RepositoryItem = rsItemComboBoxBool;  break;
               case "String":     e.RepositoryItem = rsItemTextEditProperty;  break;                    
               case "Int32":              e.RepositoryItem = rsItemSpinEdit;  break;   
               case "Collection":       e.RepositoryItem = rsItemButtonEdit;  break;
               case "Method":           e.RepositoryItem = rsItemButtonEdit;  break;
             }
            
        }


        /// <summary>
        /// 事件自动完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeProperty_ShowingEditor(object sender, CancelEventArgs e)
        {
            if (tsBtnEvent.CheckState == CheckState.Checked)
            {
                if (IsBase)
                {
                    treeProperty.FocusedNode.SetValue(1, _exFullInfoBase.BuildName + "_" + treeProperty.FocusedNode.GetValue(0).ToString());
                }
                else
                {
                    treeProperty.FocusedNode.SetValue(1, _exFullInfo.BuildName + "_" + treeProperty.FocusedNode.GetValue(0).ToString());
                }
                SaveUpdatedPropertyInfo();//保存当前状态
            }
        }


        /// <summary>
        /// 焦点离开时自动保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeProperty_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            SaveUpdatedPropertyInfo();//保存当前状态
        }
        #endregion


        #region 按钮事件


        /// <summary>
        /// 切换到属性窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnProperty_Click(object sender, EventArgs e)
        {
            if (!IsBase)
            {
                if (!buildDic.ContainsKey(buildKey))
                {
                    return;
                }
            }
            SaveUpdatedPropertyInfo();//保存当前状态
            SetPropertyButtonState(enumPropertyBtnClick.Property);
            if (IsBase)
            {
                GetPropertyToGridBase(_exFullInfoBase,enumPropertyType.Property,false);
            }
            else
            {
                GetPropertyToGrid(_exFullInfo, enumPropertyType.Property, false);
            }
        }

        /// <summary>
        /// 切换到事件窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnEvent_Click(object sender, EventArgs e)
        {
            if (!IsBase)
            {
                if (!buildDic.ContainsKey(buildKey))
                {
                    return;
                }
            }
            SaveUpdatedPropertyInfo();//保存当前状态
            SetPropertyButtonState(enumPropertyBtnClick.Event);
            if (IsBase)
            {
                GetPropertyToGridBase(_exFullInfoBase, enumPropertyType.Event, false);
            }
            else
            {
                GetPropertyToGrid(_exFullInfo, enumPropertyType.Event, false);
            }
        }
        
        
        /// <summary>
        /// 切换到全局设置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnDocument_Click(object sender, EventArgs e)
        {
            if (!IsBase)
            {
                if (!buildDic.ContainsKey(buildKey))
                {
                    return;
                }
            }
            SaveUpdatedPropertyInfo();//保存当前状态
            SetPropertyButtonState(enumPropertyBtnClick.Document);
            GetDocumentToGrid(buildDic[documentKey].BaseType);
        }


        /*------------------------------------------------------------------------------------*/

        /// <summary>
        /// 字母倒序排序Z-A
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnZA_Click(object sender, EventArgs e)
        {
            SetPropertyButtonState(enumPropertyBtnClick.ZA);
            treeColumnPropertyName.SortOrder = SortOrder.Descending;                                                                                                                                                                           
        }

        /// <summary>
        /// 字母顺序排序A-Z
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnAZ_Click(object sender, EventArgs e)
        {
            SetPropertyButtonState(enumPropertyBtnClick.AZ);
            treeColumnPropertyName.SortOrder = SortOrder.Ascending;
        }

        /*------------------------------------------------------------------------------------*/
        /// <summary>
        /// 新建方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnNewMethod_Click(object sender, EventArgs e)
        {
            using (MethodFieldCreater mfc = new MethodFieldCreater(enumPropertyType.Method, this))
            {
                mfc.ShowDialog();
            }
        }

        /// <summary>
        /// 新方法来自模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnNewMethodTemp_Click(object sender, EventArgs e)
        {
            using (CodeShop cf = new CodeShop(this,enumWhoCallCodeShop.MethodFromTemplate))
            {
                cf.ShowDialog();
            }
        }

        /// <summary>
        /// 新建字段
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnNewField_Click(object sender, EventArgs e)
        {
            using (MethodFieldCreater mfc = new MethodFieldCreater(enumPropertyType.Field, this))
            {
                mfc.ShowDialog();
            }
        }

        /// <summary>
        /// 新建自定义属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnNewCustomProperty_Click(object sender, EventArgs e)
        {
            using (MethodFieldCreater mfc = new MethodFieldCreater(enumPropertyType.CustomProperty, this))
            {
                mfc.ShowDialog();
            }
        }

        /// <summary>
        /// 新建新建自定义事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnNewCustomEvent_Click(object sender, EventArgs e)
        {
            using (MethodFieldCreater mfc = new MethodFieldCreater(enumPropertyType.CustomEvent, this))
            {
                mfc.ShowDialog();
            }
        }

        /*------------------------------------------------------------------------------------*/

        /// <summary>
        /// 添加系统属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnNewProperty_Click(object sender, EventArgs e)
        {
          //  if (treeProperty.Nodes.Count < 1)   return;
            if (IsBase)
            {
                using (PropertyEventSelector ps = new PropertyEventSelector(_exFullInfoBase.ControlFullName, enumPropertyType.Property, this))
                {
                    ps.ShowDialog();
                }
            }
            else
            {
                using (PropertyEventSelector ps = new PropertyEventSelector(_exFullInfo.ControlFullName, enumPropertyType.Property, this))
                {
                    ps.ShowDialog();
                }
            }
        }

        /// <summary>
        /// 添加系统事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnNewEvent_Click(object sender, EventArgs e)
        {
           // if (treeProperty.Nodes.Count < 1)   return;

            if (IsBase)
            {
                using (PropertyEventSelector ps = new PropertyEventSelector(_exFullInfoBase.ControlFullName, enumPropertyType.Event, this))
                {
                    ps.ShowDialog();
                }
            }
            else
            {
                using (PropertyEventSelector ps = new PropertyEventSelector(_exFullInfo.ControlFullName, enumPropertyType.Event, this))
                {
                    ps.ShowDialog();
                }
            }
        }

        /*------------------------------------------------------------------------------------*/        
        
        private void tsBtnNewInherit_Click(object sender, EventArgs e)
        {
            using (InheritItemCreater ic = new InheritItemCreater(this))
            {
                ic.ShowDialog();
            }
        }



        private void tsBtnDocument_CheckStateChanged(object sender, EventArgs e)
        {
            //if (tsBtnDocument.CheckState == CheckState.Checked)
            //{
            //    tsBtnNewInherit.Enabled = true;
            //}
            //else
            //{
            //    tsBtnNewInherit.Enabled = false;
            //}
        }

        #endregion


        #region 菜单事件
        
        /// <summary>
        /// 移除所选项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contentMenuItemDelete_Click(object sender, EventArgs e)
        {
            if (treeProperty.FocusedNode != null)
            {
                if (treeProperty.FocusedNode.GetValue("Type").ToString() != enumPropertyType.Parameter.ToString()
                    && treeProperty.FocusedNode.GetValue("Type").ToString() != enumPropertyType.Namespace.ToString()
                   )
                {
                    //从内存中移除
                    if (IsBase)
                    {
                        if (treeProperty.FocusedNode.ParentNode != null)
                        {
                            dicRemove(documentKey, treeProperty.FocusedNode, treeProperty.FocusedNode.GetValue(4).ToString());
                        }
                        else
                        {
                            dicRemove(documentKey, treeProperty.FocusedNode.GetValue(0).ToString());
                        }
                    }
                    else
                    {
                        dicRemove(_exFullInfo.BuildName, treeProperty.FocusedNode.GetValue(0).ToString());
                    }

                    //从属性表中移除
                    treeProperty.Nodes.Remove(treeProperty.FocusedNode);
                }
            }
        }

        #endregion

        private void rsItemButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index==0)
            {
                using (CodeShop cf = new CodeShop(this, enumWhoCallCodeShop.MethodForCode))
                {
                    cf.ShowDialog();
                }
            }
            else 
            {
                treeProperty.FocusedNode.SetValue("PropertyValue", "");
            }
        }





    }
}
